# -*- coding:utf-8 -*-
import netifaces
import time
import eventlet
import nmap

'''
get gateway ip
'''
def get_gateway_ip():
    # print(netifaces.gateways())
    # print(netifaces.gateways()[netifaces.AF_INET][0][0])
    if netifaces.AF_INET in netifaces.gateways().keys():
        #print netifaces.gateways()
        ip=str(netifaces.gateways()[netifaces.AF_INET][0][0])
    else:
        ip="-1"
    return ip

'''
the res has portlist,vendor,hostnames,status,addresses in default
'''
def get_port_scan_info(ip):
    scanner = nmap.PortScanner()
    scanner.scan(ip, arguments='1-65535 -O')

    portlist=[]
    for proto in scanner[ip].all_protocols():
        lport = scanner[ip][proto].keys()
        lport.sort()
        for port in lport:
            if scanner[ip][proto][port]['state'] == 'open':
                portlist.append((port, scanner[ip][proto][port]['state']))

    info = scanner[ip]
    res={}
    #res['portlist']=scanner.scaninfo()['tcp']['services']
    res['portlist']=portlist
    for k in info.keys():
        res[k]=info[k]
    return res

if __name__ == "__main__":
    port_white_list={}
    init_timeout=10
    detect_timeout=20

    eventlet.monkey_patch()
    start=time.time()
    print 'the program is initing params,please wait...'
    while True:
        ip = get_gateway_ip()
        if ip == "-1":
            print 'the network is closed,please connect'
            time.sleep(1)
            start=time.time()
            continue
        else:
            print "-------------------------------- ",ip

        stime=time.time()
        port_white_list = get_port_scan_info(ip)
        etime = time.time()
        print etime-stime

        current_time=time.time()
        if current_time-start>init_timeout:
            break
        time.sleep(1)

    print 'the port whitelist is ',port_white_list
    print 'the port whitelist established successfully,the detector is running,please wait...'
    while True:
        res = {}
        ip = get_gateway_ip()
        if ip == '-1':
            print 'the network is closed,please connect'
            time.sleep(1)
            continue
        else:
            print "Default gateway ip is ", ip

        # with eventlet.Timeout(30,False):
        start_time=time.time()
        try:
            res = get_port_scan_info(ip)
            if res["vendor"]!= port_white_list["vendor"] or res["portlist"] != port_white_list["portlist"] or res["osmatch"] != port_white_list["osmatch"]:
                print "[+]Found fake ap!"
        except KeyError:
            print 'nmap ip key not found,continue'
        print '>>>>>>>>', res
        ''' 
        if 'portlist' in res.keys():
            print("Open port list:", res['portlist'])
        if 'addresses' in res.keys():
            print("hostaddress:", res['addresses'])
        if 'status' in res.keys():
            print("host status:", res['status'])
        if 'vendor' in res.keys():
            print("venfor information:", res['vendor'])
        if 'osmatch' in res.keys():
            print('os information：',res['osmatch'])
        '''
        end_time=time.time()
        print end_time-start_time
        time.sleep(detect_timeout)
        time.sleep(2)
        #nmap更多的参数，把port_check加入，伪AP软件，wifipineapple
        #1。移交代码2。论文标记方法，里面有哪些特征，建立伪ap的软件，有什么特征3。找真实伪ap，发现特征
